﻿using System;
using System.Linq;
using System.Text;
using KSPCapability;
using UnityEngine;

public class CapabilityWeight : Part
{
	private static CapabilityAuditor _auditor;
	private static int capCount = 0;

	private bool removed = false;

	protected override void onPartStart()
	{
		base.onPartStart();
		print("partstart");
	}


	protected override void onFlightStart()
	{
		base.onFlightStart();
		print("flightstart");
		if (_auditor == null)
		{
			_auditor = new CapabilityAuditor();
			print("added auditor");
		}
		capCount++;
		print("capcount " + capCount);
	}

	private void RemoveGui()
	{
		if (!removed && _auditor != null)
		{
			print("removed weight");
			removed = true;
			capCount--;

			print("capcount " + capCount);

			if (capCount == 0)
			{
				_auditor.Destroy();
				_auditor = null;
			}

		}
	}

	protected override void onPartDetach()
	{
		base.onPartDetach();
		RemoveGui();
	}

	protected override void onPartDestroy()
	{
		base.onPartDestroy();
		RemoveGui();
	}
}

public class CapabilityAuditor
{
	protected Rect WindowPos;

	private bool _recorded = false;

	public CapabilityAuditor()
	{
		if ((WindowPos.x == 0) && (WindowPos.y == 0))
		{
			WindowPos = new Rect(Screen.width/4, Screen.height/4, 10, 10);
		}

		RenderingManager.AddToPostDrawQueue(3, DrawGui); //start the GUI
	}

	public void Destroy()
	{
		RenderingManager.RemoveFromPostDrawQueue(3, DrawGui);
	}

	private void DrawGui()
	{
		GUI.skin = HighLogic.Skin;
		WindowPos = GUILayout.Window(65500, WindowPos, WindowGui, "Capability Auditor", GUILayout.MinWidth(200));
	}

	private void WindowGui(int windowId)
	{
		GUIStyle mySty = new GUIStyle(GUI.skin.button);
		mySty.normal.textColor = mySty.focused.textColor = Color.white;
		mySty.hover.textColor = mySty.active.textColor = Color.yellow;
		mySty.onNormal.textColor =
			mySty.onFocused.textColor = mySty.onHover.textColor = mySty.onActive.textColor = Color.green;
		mySty.padding = new RectOffset(8, 8, 8, 8);

		GUILayout.BeginVertical();

		var vessel = FlightGlobals.ActiveVessel;
		var totalMass = vessel.parts.Where(p => p is CapabilityWeight).Sum(p => p.mass);
		var altitude = vessel.orbit.PeA;

		GUILayout.Label(string.Format("Audited Mass: {0:0.0}T", totalMass));

		if (vessel.orbit.PeA > 0.0)
		{
			GUILayout.Label(string.Format("{0:0} km above {1}", altitude/1000.0, vessel.orbit.referenceBody.GetName()));
			GUILayout.Label(string.Format("Inc: {0:0.0}, LAN: {1:0.0}", vessel.orbit.inclination, vessel.orbit.LAN));
		}

		var allowed = true;

		if (vessel.orbit.referenceBody.maxAtmosphereAltitude > vessel.orbit.ApA)
		{
			allowed = false;
			GUILayout.Label(string.Format("Exit atmo at {0:0.0} km", vessel.orbit.referenceBody.maxAtmosphereAltitude/1000.0));
		}
		else if (vessel.orbit.referenceBody.maxAtmosphereAltitude > vessel.orbit.PeA)
		{
			allowed = false;
			GUILayout.Label(string.Format("Bring PE out of atmo {1:0.0} / {0:0.0} km",
			                              vessel.orbit.referenceBody.maxAtmosphereAltitude/1000.0, vessel.orbit.PeA/1000.0));

		}
		else if (vessel.orbit.eccentricity > 0.005)
		{
			allowed = false;
			GUILayout.Label("Circularize orbit");
			GUILayout.Label(string.Format("AP: {0:0} PE: {1:0}", vessel.orbit.ApA, vessel.orbit.PeA));
		}

		if (!_recorded && allowed && GUILayout.Button("Recordsplosion!", mySty, GUILayout.ExpandWidth(true)))
			//GUILayout.Button is "true" when clicked
		{
			KSPCapability.CapabilityPersistance.Instance.Record(new Capability()
				                                                    {
					                                                    Body = vessel.orbit.referenceBody.bodyName,
					                                                    Altitude = altitude,
					                                                    Mass = totalMass,
					                                                    Inclination = vessel.orbit.inclination,
					                                                    LAN = vessel.orbit.LAN
				                                                    });

			_recorded = true;

			foreach (var p in vessel.parts)
			{
				p.explode();
			}
		}

		GUILayout.EndVertical();

		//DragWindow makes the window draggable. The Rect specifies which part of the window it can by dragged by, and is 
		//clipped to the actual boundary of the window. You can also pass no argument at all and then the window can by
		//dragged by any part of it. Make sure the DragWindow command is AFTER all your other GUI input stuff, or else
		//it may "cover up" your controls and make them stop responding to the mouse.
		GUI.DragWindow(new Rect(0, 0, 10000, 20));
	}

}